<template>
  <div class="about">
    <PageTitle title="XX Mall"></PageTitle>
    <van-tabs v-model="active" color="#25c9c3" animated swipeable>
      <van-tab title="登录">
        <van-form @submit="onLogin" class="login">
          <div v-if="loginType == 0" key="login_pwd" class="login_pwd">
            <van-field
              v-model="account"
              name="account"
              label="账号"
              placeholder="请输入账号"
              clearable
              :rules="[{ required: true, message: '账号不能为空' }]"
            />
            <van-field
              v-model="password"
              type="password"
              name="password"
              label="密码"
              placeholder="请输入密码"
              maxlength="16"
              clearable
              :rules="[{ required: true, message: '密码不能为空' }]"
            />
          </div>
          <div v-if="loginType == 1" key="login_sms" class="login_sms">
            <van-field
              v-model="phone"
              name="phone"
              label="手机号"
              placeholder="请输入手机号"
              clearable
              :rules="[
                { required: true, message: '手机号不能为空' },
                { validator: validatePhone, message: '请输入正确的手机号' },
              ]"
            />
            <van-field
              v-model="sms"
              center
              name="captcha"
              label="验证码"
              placeholder="请输入短信验证码"
              clearable
              :rules="[{ required: true, message: '验证码不能为空' }]"
            >
              <template #button>
                <van-button
                  size="small"
                  type="primary"
                  round
                  color="#25c9c3"
                  :disabled="!validatePhone()"
                  @click.prevent="getSms('login')"
                  >发送验证码</van-button
                >
              </template>
            </van-field>
          </div>
          <div class="pwd2sms">
            <span @click="loginType = loginType == 0 ? 1 : 0">{{
              loginType == 0 ? "手机验证码登录" : "账号密码登录"
            }}</span>
          </div>
          <div class="btn">
            <van-button
              round
              block
              type="info"
              native-type="submit"
              color="#25c9c3"
              >登录</van-button
            >
          </div>
        </van-form>
      </van-tab>
      <van-tab title="注册">
        <van-form @submit="onRegister" class="register">
          <van-field
            v-model="phone"
            name="phone"
            label="手机号"
            placeholder="请输入手机号"
            clearable
            :rules="[
              { required: true, message: '手机号不能为空' },
              { validator: validatePhone, message: '请输入正确的手机号' },
            ]"
          />
          <van-field
            v-model="sms"
            center
            name="captcha"
            label="验证码"
            placeholder="请输入短信验证码"
            clearable
            :rules="[{ required: true, message: '验证码不能为空' }]"
          >
            <template #button>
              <van-button
                size="small"
                type="primary"
                round
                color="#25c9c3"
                :disabled="!validatePhone()"
                @click.prevent="getSms('register')"
                >发送验证码</van-button
              >
            </template>
          </van-field>
          <van-field
            v-model="password"
            type="password"
            name="password"
            label="密码"
            placeholder="请输入密码"
            maxlength="16"
            clearable
            :rules="[
              { required: true, message: '密码不能为空' },
              { validator: validatePwd, message: '请输入6-16位密码' },
            ]"
          />
          <van-field
            v-model="confirmPwd"
            type="password"
            name="confirmPwd"
            label="确认密码"
            placeholder="请再次输入密码"
            maxlength="16"
            clearable
            :rules="[
              { required: true, message: '密码不能为空' },
              { validator: comparePwd, message: '两次输入密码不相同' },
              { validator: validatePwd, message: '请输入6-16位密码' },
            ]"
          />
          <div class="btn">
            <van-button
              round
              block
              type="info"
              native-type="submit"
              color="#25c9c3"
              >注册</van-button
            >
          </div>
        </van-form>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import PageTitle from "@/components/PageTitle";
import { mapMutations } from "vuex";
export default {
  name: "Login",
  data() {
    return {
      loginType: 0,
      account: "13565659698",
      password: "admin8899",
      confirmPwd: "",
      phone: "13565659698",
      sms: "",
      smskey: null,
      active: 0,
    };
  },
  components: {
    PageTitle,
  },
  methods: {
    ...mapMutations(["changeLoading", "saveToken"]),
    onLogin(val) {
      // console.log("login", val);
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "登录中...",
      });
      let url = this.loginType == 0 ? "/api/login" : "/api/login/mobile";
      this.axios
        .post(url, val)
        .then((d) => {
          console.log(url.replace("/api/", ""), d.data);
          this.$toast.clear();
          if (d.data.status == 200) {
            this.$toast.success({
              message: "登录成功",
              forbidClick: true,
              onClose: () => {
                this.saveToken(d.data.data.token); // 存储token
                if (window.history.length <= 1) {
                  this.$router.push("/");
                } else {
                  this.$router.go(-1);
                }
              },
            });
          } else {
            this.$toast.fail(d.data.msg);
          }
        })
        .catch(() => {
          this.$toast.clear();
          this.$toast.fail("请求失败");
        });
    },
    onRegister({ phone, captcha, password }) {
      // console.log("register", { phone, captcha, password });
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "注册中...",
      });
      this.axios
        .post("/api/register", {
          account: phone,
          captcha,
          password,
        })
        .then((d) => {
          console.log("register", d.data);
          this.$toast.clear();
          if (d.data.status == 200) {
            this.$toast.success({
              message: "注册成功",
              onOpened: () => {
                this.account = phone;
                this.active = 0;
                this.loginType = 0;
              },
            });
          } else {
            this.$toast.fail(d.data.msg);
          }
        })
        .catch(() => {
          this.$toast.clear();
          this.$toast.fail("请求失败");
        });
    },
    validatePhone() {
      return /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/.test(
        this.phone
      );
    },
    validatePwd(val) {
      return val.length >= 6 && val.length <= 16;
    },
    comparePwd(val) {
      return val == this.password;
    },
    getSmsKey() {
      this.changeLoading(true);
      this.$axios.get("/api/verify_code").then((d) => {
        console.log("verify_code", d.data);
        this.smskey = d.data.data.key;
        this.changeLoading(false);
      });
    },
    getSms(type) {
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "发送中...",
      });
      this.$axios
        .post("/api/register/verify", {
          key: this.smskey,
          phone: this.phone,
          type,
        })
        .then((d) => {
          console.log("verify", type, d.data);
          this.$toast.clear();
          if (d.data.status == 200) {
            this.$toast.success("验证码发送成功");
          } else {
            this.$toast.fail(d.data.msg.replace("！", ""));
          }
        })
        .catch(() => {
          this.$toast.fail("发送失败");
        });
    },
  },
  created() {
    this.getSmsKey();
  },
};
</script>

<style lang="less" scoped>
.van-form {
  min-height: calc(100vh - 100px);
  box-sizing: border-box;
  padding-top: 25px;
  .pwd2sms {
    height: 15px;
    padding: 10px 16px;
    padding-bottom: 0;
    font-size: 12px;
    font-weight: lighter;
    color: #25c9c3;
    text-align: right;
    span {
      cursor: pointer;
    }
  }
  .btn {
    margin: 25px 16px;
  }
}
</style>